package com.fz.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.fz.common.Result;
import com.fz.controller.request.BookPageRequest;
import com.fz.pojo.Admin;
import com.fz.pojo.Book;
import com.fz.service.BookService;
import com.fz.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/book")
@CrossOrigin
@Slf4j
public class BookController {
    @Autowired
    private BookService bookService;


    //String userDir = System.getProperty("user.dir");//获取当前项目的根目录
    private static final String BASE_FILE_PATH = System.getProperty("user.dir") + "/files/";

    //上传
    @PostMapping("/file/upload")
    public Result file(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StrUtil.isBlank(originalFilename)){
            return Result.error("文件上传失败");
        }
        long flag = System.currentTimeMillis();
        String filePath = BASE_FILE_PATH + flag + "_" + originalFilename;
        try {
            FileUtil.mkParentDirs(filePath);//创建父级目录
            file.transferTo(FileUtil.file(filePath));
            Admin currentAdmin = TokenUtils.getCurrentAdmin();
            String token = TokenUtils.genToken(currentAdmin.getId().toString(), currentAdmin.getPassword(),3);//3天过期
            String url="http://localhost:9090/api/book/file/download/" + flag + "?&token=" +token;

            if (originalFilename.endsWith("png")||originalFilename.endsWith("jpg")||originalFilename.endsWith("pdf")){
                url+="&play=1";//play=1可以已预览的方式打开
            }
            return Result.success(url);
        } catch (Exception e) {
            log.info("文件上传失败" + e);

        }
        return Result.error("文件上传失败");

    }

    //下载
    @GetMapping("/file/download/{flag}")
    public void download(@PathVariable String flag, @RequestParam(required = false) String play, HttpServletResponse response) {
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(BASE_FILE_PATH);
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                String realName = fileName.substring(fileName.indexOf("_") + 1);
                if ("1".equals(play)) {
                    response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(realName, "UTF-8"));
                } else {
                    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realName, "UTF-8"));
                }
                byte[] bytes = FileUtil.readBytes(BASE_FILE_PATH + fileName);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }

        } catch (Exception e) {
            log.error("文件下载失败", e);
        }

    }

    //查询用户
    @GetMapping("/list")
    public Result list() {
        List<Book> book = bookService.list();
        return Result.success(book);
    }

    //通过id查询种类
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        return Result.success(book);
    }

    //分页
    @GetMapping("/page")
    public Result page(BookPageRequest bookPageRequest) {
        return Result.success(bookService.page(bookPageRequest));
    }


    // 添加
    @PostMapping("/addBook")
    public Result addBook(@RequestBody Book book) {//这里要加@RequestBody 如果不加添加都是null
        bookService.addBook(book);
        return Result.success();
    }

    //更新
    @PutMapping("/update")
    public Result update(@RequestBody Book book) {
        bookService.update(book);
        return Result.success();
    }

    //删除
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        bookService.deleteById(id);
        return Result.success();
    }


}
